<template>
  <div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-6">合同管理系统测试页面</h1>

    <!-- 创建合同表单 -->
    <div class="bg-white rounded-lg shadow p-6 mb-8">
      <h2 class="text-xl font-semibold mb-4">创建测试合同</h2>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">合同名称</label>
          <input v-model="newContract.name" type="text" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">合同状态</label>
          <select v-model="newContract.status" class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            <option value="DRAFT">草稿</option>
            <option value="ACTIVE">生效中</option>
            <option value="COMPLETED">已完成</option>
            <option value="TERMINATED">已终止</option>
          </select>
        </div>

        <div class="md:col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-1">客户信息</label>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <input v-model="newCustomer.companyName" type="text" placeholder="客户公司名称" class="w-full px-4 py-2 border border-gray-300 rounded-md">
            <input v-model="newCustomer.contactName" type="text" placeholder="联系人姓名" class="w-full px-4 py-2 border border-gray-300 rounded-md">
            <input v-model="newCustomer.contactInfo" type="text" placeholder="联系电话" class="w-full px-4 py-2 border border-gray-300 rounded-md">
          </div>
        </div>

        <div class="md:col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-1">项目经理</label>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <input v-model="newProjectManager.name" type="text" placeholder="项目经理姓名" class="w-full px-4 py-2 border border-gray-300 rounded-md">
            <input v-model="newProjectManager.contactInfo" type="text" placeholder="联系电话" class="w-full px-4 py-2 border border-gray-300 rounded-md">
            <select v-model="newProjectManager.position" class="w-full px-4 py-2 border border-gray-300 rounded-md">
              <option value="PROJECT_MANAGER">项目经理</option>
              <option value="TECHNICAL_LEAD">技术总监</option>
              <option value="DEVELOPER">开发人员</option>
            </select>
          </div>
        </div>
      </div>

      <button @click="createTestContract" class="mt-4 px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors">
        创建合同
      </button>
    </div>

    <!-- 查询合同 -->
    <div class="bg-white rounded-lg shadow p-6 mb-8">
      <h2 class="text-xl font-semibold mb-4">查询合同</h2>

      <div class="flex flex-col sm:flex-row gap-4 mb-4">
        <input v-model="searchStatus" type="text" placeholder="输入状态（如：ACTIVE）" class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
        <button @click="searchContracts" class="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors">
          查询
        </button>
      </div>

      <div v-if="loading" class="text-center py-4">
        <div class="inline-block h-8 w-8 animate-spin rounded-full border-4 border-gray-200 border-t-blue-500"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>

      <div v-else-if="contracts.length > 0" class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead>
          <tr>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">合同名称</th>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户</th>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">项目经理</th>
            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="contract in contracts" :key="contract.id">
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ contract.id }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ contract.name }}</td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                      :class="{
                        'bg-yellow-100 text-yellow-800': contract.status === 'DRAFT',
                        'bg-green-100 text-green-800': contract.status === 'ACTIVE',
                        'bg-gray-100 text-gray-800': contract.status === 'COMPLETED',
                        'bg-red-100 text-red-800': contract.status === 'TERMINATED'
                      }">
                  {{ getStatusText(contract.status) }}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ contract.customer?.companyName || '-' }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ contract.projectManager?.name || '-' }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-blue-500 hover:text-blue-700 cursor-pointer"
                @click="viewContractDetails(contract.id)">
              查看详情
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <div v-else class="text-center py-8 text-gray-500">
        没有找到匹配的合同
      </div>
    </div>

    <!-- 合同详情模态框 -->
    <div v-if="selectedContract" class="fixed inset-0 z-50 overflow-y-auto" @click.self="closeModal">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                  合同详情: {{ selectedContract.name }}
                </h3>
                <div class="space-y-4">
                  <div class="grid grid-cols-3 gap-4">
                    <div>
                      <p class="text-sm font-medium text-gray-500">合同ID</p>
                      <p class="text-sm text-gray-900">{{ selectedContract.id }}</p>
                    </div>
                    <div>
                      <p class="text-sm font-medium text-gray-500">状态</p>
                      <p class="text-sm text-gray-900">{{ getStatusText(selectedContract.status) }}</p>
                    </div>
                    <div>
                      <p class="text-sm font-medium text-gray-500">创建时间</p>
                      <p class="text-sm text-gray-900">{{ formatDateTime(selectedContract.createTime) }}</p>
                    </div>
                  </div>

                  <div>
                    <p class="text-sm font-medium text-gray-500">客户信息</p>
                    <div class="mt-1 grid grid-cols-1 gap-2 sm:grid-cols-2">
                      <p class="text-sm text-gray-900">公司名称: {{ selectedContract.customer?.companyName || '-' }}</p>
                      <p class="text-sm text-gray-900">联系人: {{ selectedContract.customer?.contactName || '-' }}</p>
                      <p class="text-sm text-gray-900">联系电话: {{ selectedContract.customer?.contactInfo || '-' }}</p>
                    </div>
                  </div>

                  <div>
                    <p class="text-sm font-medium text-gray-500">项目经理</p>
                    <div class="mt-1 grid grid-cols-1 gap-2 sm:grid-cols-2">
                      <p class="text-sm text-gray-900">姓名: {{ selectedContract.projectManager?.name || '-' }}</p>
                      <p class="text-sm text-gray-900">职位: {{ getPositionText(selectedContract.projectManager?.position) || '-' }}</p>
                      <p class="text-sm text-gray-900">电话: {{ selectedContract.projectManager?.contactInfo || '-' }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm"
                    @click="closeModal">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作结果弹窗 -->
    <div v-if="showResultModal" class="fixed inset-0 z-50 overflow-y-auto" @click.self="closeResultModal">
      <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                <div class="flex justify-center mb-4">
                  <div class="h-16 w-16 rounded-full flex items-center justify-center" :class="resultTypeClass">
                    <i :class="getResultIcon(resultType)" class="text-white text-2xl"></i>
                  </div>
                </div>
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-2">
                  {{ resultTitle }}
                </h3>
                <p class="text-base text-gray-500 mb-6">
                  {{ resultMessage }}
                </p>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm"
                    @click="handleResultModalAction">
              {{ resultActionText }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import contractService from '@/services/contractService';

// 数据状态
const newContract = ref({
  name: '测试合同',
  status: 'DRAFT'
});
const newCustomer = ref({
  companyName: '测试客户有限公司',
  contactName: '张三',
  contactInfo: '13900139000'
});
const newProjectManager = ref({
  name: '李四',
  contactInfo: '13800138000',
  position: 'PROJECT_MANAGER'
});

const searchStatus = ref('ACTIVE');
const contracts = ref([]);
const loading = ref(false);
const selectedContract = ref(null);
const showResultModal = ref(false);
const resultType = ref('success');
const resultTitle = ref('');
const resultMessage = ref('');
const resultActionText = ref('确定');

// 路由相关
const route = useRoute();
const router = useRouter();

// 创建测试合同
const createTestContract = async () => {
  try {
    const contractData = {
      ...newContract.value,
      customer: newCustomer.value,
      projectManager: newProjectManager.value,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };

    // 确保status是字符串类型
    contractData.status = String(contractData.status);

    const response = await contractService.createContract(contractData);

    // 显示成功弹窗
    showResultModal.value = true;
    resultType.value = 'success';
    resultTitle.value = '创建成功';
    resultMessage.value = `合同创建成功！ID: ${response.data.id}`;
    resultActionText.value = '返回列表';

    // 保存创建的合同ID，用于返回后定位
    // eslint-disable-next-line no-unused-vars
    const createdContractId = response.data.id;

    // 弹窗确认后的回调
    const onConfirm = () => {
      // 刷新合同列表
      searchContracts();

      // 如果需要，可以导航到合同详情页
      // router.push(`/contracts/${createdContractId}`);
    };

    // 存储回调函数
    window.onContractModalConfirm = onConfirm;

  } catch (error) {
    console.error('创建合同失败:', error);

    // 显示失败弹窗
    showResultModal.value = true;
    resultType.value = 'error';
    resultTitle.value = '创建失败';
    resultMessage.value = error.response?.data?.message || `创建合同失败: ${error.message}`;
    resultActionText.value = '关闭';
  }
};

// 处理弹窗确认操作
const handleResultModalAction = () => {
  showResultModal.value = false;

  // 执行成功回调（如果有）
  if (resultType.value === 'success' && window.onContractModalConfirm) {
    window.onContractModalConfirm();
    // 清除回调
    delete window.onContractModalConfirm;
  }

  // 如果是返回列表操作，这里可以添加路由返回逻辑
  if (resultActionText.value === '返回列表') {
    // 返回到当前页面（刷新）
    router.replace(route.fullPath);
  }
};

// 关闭结果弹窗
const closeResultModal = () => {
  showResultModal.value = false;
};

// 查询合同
const searchContracts = async () => {
  if (!searchStatus.value) {
    // 这里可以保留通知提示，用于非弹窗场景
    // showNotification('请输入合同状态', 'warning');
    return;
  }

  loading.value = true;
  try {
    // 确保searchStatus是字符串类型
    const response = await contractService.getContractsByStatus(String(searchStatus.value));
    contracts.value = response.data;

    if (contracts.value.length === 0) {
      // showNotification('未找到匹配的合同', 'info');
    }
  } catch (error) {
    console.error('查询合同失败:', error);
    // showNotification('查询合同失败: ' + (error.response?.data?.message || error.message), 'error');
  } finally {
    loading.value = false;
  }
};

// 查看合同详情
const viewContractDetails = async (id) => {
  try {
    const response = await contractService.getContractById(id);
    selectedContract.value = response.data;
  } catch (error) {
    console.error('获取合同详情失败:', error);
    // showNotification('获取合同详情失败: ' + (error.response?.data?.message || error.message), 'error');
  }
};

// 关闭模态框
const closeModal = () => {
  selectedContract.value = null;
};

// 获取结果图标
const getResultIcon = (type) => {
  switch (type) {
    case 'success': return 'fa-check';
    case 'error': return 'fa-times';
    case 'warning': return 'fa-exclamation-triangle';
    case 'info': return 'fa-info-circle';
    default: return 'fa-info';
  }
};

// 状态文本转换
const getStatusText = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'ACTIVE': '生效中',
    'COMPLETED': '已完成',
    'TERMINATED': '已终止'
  };
  return statusMap[status] || status;
};

// 职位文本转换
const getPositionText = (position) => {
  const positionMap = {
    'PROJECT_MANAGER': '项目经理',
    'TECHNICAL_LEAD': '技术总监',
    'DEVELOPER': '开发人员'
  };
  return positionMap[position] || position;
};

// 格式化日期时间
const formatDateTime = (isoString) => {
  if (!isoString) return '-';
  const date = new Date(isoString);
  return date.toLocaleString();
};

// 计算属性：结果类型对应的样式类
const resultTypeClass = computed(() => {
  switch (resultType.value) {
    case 'success': return 'bg-green-500';
    case 'error': return 'bg-red-500';
    case 'warning': return 'bg-yellow-500';
    case 'info': return 'bg-blue-500';
    default: return 'bg-gray-500';
  }
});

// 组件挂载时执行
onMounted(() => {
  console.log('页面已加载，当前路由:', route.fullPath);
  searchContracts(); // 自动查询合同
});
</script>

<style scoped>
/* 图标样式 */
:deep(.fa) {
  font-family: "Font Awesome 5 Free";
  font-weight: 900;
}
</style>